/*
 * Copyright © 2010 SenseForce.com.
 * The Software shall be used for Good, not Evil.
 */

package com.senseforce.midlets;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Date;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.rms.*;

/**
 * @author jcccn
 * @site http://www.senseforce.com/
 */
public class StartRMS extends MIDlet implements CommandListener {
    private Display display;
    private Form mainForm;
    private RecordStore rs = null;
    private Command addCommand = new Command("Create", Command.ITEM, 1);
     private Command addRecordCommand = new Command("Add", Command.ITEM, 1);
    private Command deleteCommand = new Command("Del", Command.ITEM, 1);
    private Command openCommand = new Command("Open", Command.ITEM, 1);
    private Command closeCommand = new Command("Close", Command.ITEM, 1);
    private Command exitCommand = new Command("Exit", Command.EXIT, 1);
    private Command okCommand = new Command("OK", Command.OK, 1);
    private Command cancelCommand  = new Command("Cancel", Command.CANCEL, 1);
    private TextBox rsName = new TextBox("NameOfRecordStore", "", 32, TextField.ANY);
    private Alert promote = new Alert("The Result");
    private int status = 0;
    private int count = 0;
    private int recordID;

    public StartRMS() {
        super();
        rsName.addCommand(okCommand);
        rsName.addCommand(cancelCommand);
        promote.setTimeout(8000);
    }

    public void startApp() {
        display = Display.getDisplay(this);
        mainForm = new Form("Test Record Store");
        mainForm.addCommand(addCommand);
        mainForm.addCommand(addRecordCommand);
        mainForm.addCommand(deleteCommand);
        mainForm.addCommand(openCommand);
        mainForm.addCommand(closeCommand);
        mainForm.addCommand(exitCommand);
        display.setCurrent(mainForm);
        mainForm.setCommandListener(this);
        rsName.setCommandListener(this);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    public void commandAction(Command c, Displayable d) {
        if (c == exitCommand) {
            try {
                destroyApp(true);
            } catch (Exception e) {
                
            }
            notifyDestroyed();
        }
        if (c == addCommand) {
            display.setCurrent(rsName);
            status = 0;         //当前状态为打开记录仓库
        }
        if (c == addRecordCommand) {
            try {
                System.out.println(this.addRecord(rs.getName()));
            } catch (RecordStoreNotOpenException ex) {
                
            }
        }
        if (c == deleteCommand) {
            display.setCurrent(rsName);
            status  = 1;        //删除
        }
        if (c == openCommand) {
            display.setCurrent(rsName);
            status = 2;         //打开
        }
        if (c == closeCommand) {
            display.setCurrent(rsName);
            status = 3;         //关闭
        }
        if (c == okCommand) {
            switch(status) {
                case 0: {
                    String result = creatRS(rsName.getString());
                    promote.setString(result);
                    show();
                    display.setCurrent(promote, mainForm);
                }
                    break;
                case 1: {
                    String result = deleteRS(rsName.getString());
                    promote.setString(result);
                    show();
                    display.setCurrent(promote, mainForm);
                }
                    break;
                case 2: {
                    String result = openRS(rsName.getString());
                    promote.setString(result);
                    show();
                    display.setCurrent(promote, mainForm);
                }
                    break;
                case 3: {
                    String result = closeRS(rsName.getString());
                    promote.setString(result);
                    show();
                    display.setCurrent(promote, mainForm);
                }
                    break;
            }
            if (c == cancelCommand) {
                display.setCurrent(mainForm);
            }
        }
    }

    public String creatRS(String name) {
        boolean notExisting = false;
        try {
            rs = RecordStore.openRecordStore(name, false, RecordStore.AUTHMODE_PRIVATE, false);
            count ++;
        } catch (RecordStoreNotFoundException e) {
            notExisting = true;
        } catch (Exception e) {
            System.out.println(e);
        }
        if (notExisting) {
            try {
                rs = RecordStore.openRecordStore(name, true, RecordStore.AUTHMODE_PRIVATE, false);
                count ++;
            } catch (Exception e) {
            }
            return "A Record Store created and opened succesfully!";
        }
        else {
            return "The existing Record Store opened!";
        }
    }

    public String openRS(String name) {
        if (rs == null) {
            return "No existing Record Store!";
        }
        String p = "";
        try {
            rs = RecordStore.openRecordStore(name, false);
            count ++;
            //for more information
            System.out.println("created time:"+(new Date(rs.getLastModified())));
            System.out.println("record name:"+rs.getName());
            System.out.println("records count:"+Integer.toString(rs.getNumRecords()));
            System.out.println("rs size:"+rs.getSize());
            System.out.println("available size:"+rs.getSizeAvailable());
            System.out.println("version:"+rs.getVersion());
        } catch (RecordStoreNotFoundException e) {
            p = "Record Store not existing!";
        }
        catch (RecordStoreException e) {
            p = "Record Store exception!";
            System.out.println(e);
        }
        if (p.equals("")) {
            return "Record Store opened successfully!";
        }
        else {
             return p;
        }
    }

    public String deleteRS(String name) {
        if (rs == null) {
            return "No existing Record Store!";
        }
        String p = "";
        try {
            RecordStore.deleteRecordStore(name);
            rs = null;
            count = 0;
        } catch (RecordStoreNotOpenException e) {
            p = "Record Store not opened!";
        } catch (RecordStoreNotFoundException e) {
            p = "Record Store not found!";
        } catch (RecordStoreException e) {
            p = "Record Store exception!";
            System.out.println(e);
        }
        if (p.equals("")) {
            return "Record Store deleted successfully!";
        }
        else {
             return p;
        }
    }

    public String closeRS(String name) {
        String p = "";
        try {
            rs.closeRecordStore();
            count --;
        } catch (RecordStoreNotOpenException e) {
            p = "Record Store not opened!";
        } catch (RecordStoreException e) {
            p = "Record Store exception!";
            System.out.println(e);
        }
        if (p.equals("")) {
            return "Record Store closed successfully!";
        }
        else {
             return p;
        }
    }

    public String addRecord(String name) {
        try {
            //add record
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(baos);
            dos.writeBoolean(false);
            dos.writeInt(15);
            dos.writeUTF("HiTao!");
            byte[] data = baos.toByteArray();
            dos.close();
            baos.close();
            //just for io test
            ByteArrayInputStream bais = new ByteArrayInputStream(data);
            DataInputStream dis = new DataInputStream(bais);
            boolean flag = dis.readBoolean();
            int intValue = dis.readInt();
            String strValue = dis.readUTF();
            dis.close();
            bais.close();

            RecordStore theRS = RecordStore.openRecordStore(name, false);
            String str = new String(data);
            str = "HiTao!";
            System.out.println("str:"+str);
            recordID = theRS.addRecord(str.getBytes(), 0, 3);

            RecordFilter rf = new MyRecordFilter();
            RecordEnumeration re = theRS.enumerateRecords(rf, null, flag);
            if (re.hasNextElement()) {
                
            }

            String recordStr = new String(theRS.getRecord(recordID));
            theRS.closeRecordStore();
            System.out.println("add a new record:" + recordStr + ",with id:" + recordID+",size-"+theRS.getRecordSize(recordID));
            return recordStr.concat(":id=" + recordID);
        } catch (IOException ex) {
            return "IOException!";
        } catch (RecordStoreException ex) {
            return "RecordStoreException!";
        }
    }

    public void show() {
        mainForm.deleteAll();
        if (rs == null) {
            mainForm.addCommand(okCommand);
            mainForm.addCommand(deleteCommand);
            mainForm.addCommand(openCommand);
            mainForm.addCommand(closeCommand);
            mainForm.addCommand(exitCommand);
            mainForm.append(new StringItem(null, "Current RS opened time:" + count));
        }
        else {
            mainForm.addCommand(okCommand);
            mainForm.addCommand(deleteCommand);
            mainForm.addCommand(openCommand);
            mainForm.addCommand(closeCommand);
            mainForm.addCommand(exitCommand);
        }
    }

    class MyRecordFilter implements RecordFilter {

        public boolean matches(byte[] candidate) {
            return true;
        }
        
    }
}